package org.jsola.contract.common;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.extern.slf4j.Slf4j;
import org.jsola.contract.exception.ContractException;
import org.jsola.contract.service.impl.AsianFontProvider;
import org.jsoup.Jsoup;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author JanusMix
 */
@Slf4j
public class PdfHelper {

    private static final String css = "/*!\n" +
            " * Quill Editor v2.0.0-dev.3\n" +
            " * https://quilljs.com/\n" +
            " * Copyright (c) 2014, Jason Chen\n" +
            " * Copyright (c) 2013, salesforce.com\n" +
            " */.ql-align-center{text-align:center}.ql-editor */";

    /**
     * 导出富文本为pdf
     *
     * @param path 文件路径
     * @param content 富文本内容，需转义之后
     */
    public static void exportPdf(String path, String content) {
        //创建A4大小的itext的文档
        Document document = new Document(PageSize.LETTER);
        try {
            //pdf写到文件路径下
            PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));
            document.open();
            //解析富文本html
            org.jsoup.nodes.Document contentDoc = Jsoup.parseBodyFragment(content);
            org.jsoup.nodes.Document.OutputSettings outputSettings = new org.jsoup.nodes.Document.OutputSettings();
            outputSettings.syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
            contentDoc.outputSettings(outputSettings);
            String parsedHtml = contentDoc.outerHtml();
            byte[] bytes = parsedHtml.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            //css
            InputStream cssIs = new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8));
            //导出
            XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, byteArrayInputStream, cssIs, StandardCharsets.UTF_8, new AsianFontProvider());
            byteArrayInputStream.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ContractException("导出pdf失败，" + e.getMessage());
        }
    }

}
